﻿@using Project.Constraints.Models.Request
@using Project.Constraints.UI.Table
@using Project.Web.Shared.Utils
@using System.Linq.Expressions
@inherits BasicComponent
@typeparam TData
@typeparam TQuery where TQuery : IRequest, new()

<div class="queryarea">
    <div class="condition">
        <StackPanel>
            @if (Options?.EnabledAdvancedQuery ?? false)
            {
                @* <ConditionBuilder Columns=@Options.Columns @bind-Info="conditionInfo" Localizer="Localizer" TableLocalizer="TableLocalizer" OnChanged="CacheInfo" @ref=insRef></ConditionBuilder> *@
                <SingleConditionBuilder Item="@Options.Query.Condition" Columns="@Options.Columns" OnNameChanged="CacheInfo" Localizer="Localizer" TableLocalizer="TableLocalizer"></SingleConditionBuilder>
            }
            @UI.BuildButton(this).OnClick(Search).Text(TableLocalizer["TableButtons.Query"]).Primary().Render()
            @if (Options?.EnabledAdvancedQuery ?? false)
            {
                @UI.BuildButton(this).OnClick(() => AdvanceModalVisible = true).Text(TableLocalizer["TableButtons.AdvancedQuery"]).Render()
            }
            @if (Options?.ShowAddButton ?? false)
            {
                @UI.BuildButton(this).OnClick(HandleAdd).Text(TableLocalizer["TableButtons.Add"]).Primary().Render()
            }
            @if ((Options?.ShowExportButton ?? false) || (Options?.Exportable ?? false))
            {
                @UI.BuildButton(this).OnClick(Export).Text(TableLocalizer["TableButtons.Export"]).Primary().Render()
            }
            @if (Options?.ShowImportButton == true)
            {
                <label for="@($"{typeof(TData).Name}_import")">
                    <InputFile id="@($"{typeof(TData).Name}_import")" hidden OnChange="ImportAsync" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"></InputFile>
                    @UI.BuildFakeButton(new() { ButtonType = ButtonType.Primary, Text = TableLocalizer["TableButtons.Import"] })
                </label>
                @UI.BuildButton(this).Primary().Text(TableLocalizer["TableButtons.ImportTemplate"]).OnClick(DownloadImportTemplate).Render()
            }
            @if (ChildContent != null)
            {
                @ChildContent
            }
        </StackPanel>
    </div>
</div>
@if (Options?.EnabledAdvancedQuery ?? false)
{
    <MModal @bind-Visible="AdvanceModalVisible" Title=@TableLocalizer["TableButtons.AdvancedQuery"] Width="800px" HideDefaultFooter>
        <AdvanceQuery TData=TData
                      Localizer="Localizer"
                      TableLocalizer="TableLocalizer"
                      @bind-Condition="Options.Query.Condition"
                      ShowExportButton=@(Options.ShowExportButton)
                      OnConfirmToSearch=AdvanceSearch
                      OnConfirmToExport=AdvanceExport>
        </AdvanceQuery>
    </MModal>
}
@code {
    [Parameter, NotNull] public TableOptions<TData, TQuery>? Options { get; set; }
    [Parameter] public RenderFragment? ChildContent { get; set; }
    [Inject, NotNull] IStringLocalizer<TData>? Localizer { get; set; }
    [Inject, NotNull] IStringLocalizer<TableOptions>? TableLocalizer { get; set; }
    [Inject, NotNull] IProtectedLocalStorage? LocalStorage { get; set; }
    [Parameter] public EventCallback DownloadImportTemplate { get; set; }
    private bool AdvanceModalVisible = false;
    // ElementReference? elementReference;
    readonly string cache_key = $"TableOptions_{typeof(TData).Name}_ConditionAction";
    async Task CacheInfo()
    {
        var storageValue = new ConditionStorage()
            {
                Name = Options.Query.Condition.Name,
                CompareType = Options.Query.Condition.CompareType
            };
        await LocalStorage.SetAsync(cache_key, storageValue);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            try
            {
                var result = await LocalStorage.GetAsync<ConditionStorage>(cache_key);
                if (result.Success)
                {
                    Options.Query.Condition.Name = result.Value!.Name;
                    Options.Query.Condition.CompareType = result.Value!.CompareType;
                    await InvokeAsync(StateHasChanged);
                }
            }
            catch
            {

            }

        }
    }

    async Task HandleAdd()
    {
        if (Options?.OnAddItemAsync == null)
        {
            return;
        }
        var result = await Options.OnAddItemAsync();
        if (result is null) return;
        if (UI.ShowError(result))
        {
            await Options.RefreshAsync();
        }
    }

    public async Task Search()
    {
        if (Options == null)
        {
            return;
        }
        Options.Query.PageIndex = 1;
        Options.Query.ExpressionSolveType = SolveType.TopOnly;
        await Options.RefreshAsync();
    }

    public async Task Export()
    {
        if (Options == null)
        {
            return;
        }
        Options.Query.ExpressionSolveType = SolveType.TopOnly;
        await Options.ExportAsync();
    }


    public async void AdvanceExport()
    {
        if (Options == null)
        {
            return;
        }
        Options.Query.ExpressionSolveType = SolveType.All;
        AdvanceModalVisible = false;
        await Options.ExportAsync();
    }

    public async Task AdvanceSearch()
    {
        if (Options == null)
        {
            return;
        }
        Options.Query.PageIndex = 1;
        Options.Query.ExpressionSolveType = SolveType.All;
        AdvanceModalVisible = false;
        await Options.RefreshAsync();
    }

    public async Task ImportAsync(InputFileChangeEventArgs e)
    {
        if (e.File.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        {
            UI.AlertError("文件类型错误", "请将Excel文件转为xlsx类型");
            return;
        }
        // 10m
        using var fileStream = e.File.OpenReadStream(1024 * 1000 * 10);
        using var ms = new MemoryStream();
        await fileStream.CopyToAsync(ms);
        await (Options.OnImportAsync?.Invoke(ms) ?? Task.CompletedTask);
    }
}

